import request from '@/utils/request'
import download from '@/utils/download'

// 查询数据库列表
export function listDatabase(query) {
  return request({
    url: '/system/sync/database/list',
    method: 'get',
    params: query
  })
}

// 查询数据库详细
export function getDatabase(dbId) {
  return request({
    url: '/system/sync/database/' + dbId,
    method: 'get'
  })
}

// 新增数据库
export function addDatabase(data) {
  return request({
    url: '/system/sync/database',
    method: 'post',
    data: data
  })
}

// 修改数据库
export function updateDatabase(data) {
  return request({
    url: '/system/sync/database',
    method: 'put',
    data: data
  })
}

// 删除数据库
export function delDatabase(dbId) {
  return request({
    url: '/system/sync/database/' + dbId,
    method: 'delete'
  })
}

// 测试数据库连接
export function testDatabaseConnection(dbId) {
  return request({
    url: '/system/sync/database/test/' + dbId,
    method: 'get'
  })
}

// 查询数据库选项列表
export function listDatabaseOptions() {
  return request({
    url: '/system/sync/database/options',
    method: 'get'
  })
}

// 本地备份数据库
export function backupDatabase(dbId) {
  return request({
    url: '/system/sync/database/backup/' + dbId,
    method: 'get'
  })
}

// 远程备份数据库
export function remoteBackupDatabase(dbId, targetServerId, backupPath) {
  return request({
    url: '/system/sync/database/remote-backup/' + dbId,
    method: 'post',
    data: { targetServerId, backupPath }
  })
}

// 获取数据库表结构
export function getDatabaseTables(dbId) {
  return request({
    url: '/system/sync/database/tables/' + dbId,
    method: 'get'
  })
}

// 获取表字段结构
export function getTableColumns(dbId, tableName) {
  return request({
    url: '/system/sync/database/columns/' + dbId + '/' + tableName,
    method: 'get'
  })
}

// 执行SQL查询
export function executeQuery(dbId, sql) {
  return request({
    url: '/system/sync/database/execute/' + dbId,
    method: 'post',
    data: { sql }
  })
}

/**
 * 下载备份文件
 * @param fileName 文件名
 */
export function downloadBackupFile(fileName) {
  return new Promise((resolve, reject) => {
    try {
      import('@/utils/auth').then(auth => {
        const token = auth.getToken();
        const baseURL = process.env.VUE_APP_BASE_API;
        const downloadUrl = baseURL + '/common/download?fileName=' + encodeURIComponent(fileName) + '&delete=false';
        
        const xhr = new XMLHttpRequest();
        xhr.open('GET', downloadUrl, true);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        
        xhr.onload = function() {
          if (xhr.status === 200) {
            console.log('下载成功，文件大小:', xhr.response.size, 'bytes');
            const blob = new Blob([xhr.response]);
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            resolve({ success: true, fileName: fileName });
          } else {
            console.error('下载失败，状态码:', xhr.status);
            reject(new Error('下载失败，状态码: ' + xhr.status));
          }
        };
        
        xhr.onerror = function() {
          console.error('下载出错');
          reject(new Error('下载出错'));
        };
        
        xhr.send();
      });
    } catch (error) {
      console.error('下载异常:', error);
      reject(error);
    }
  });
}

// 更新数据库备份设置
export function updateDatabaseBackupSettings(data) {
  return request({
    url: '/system/sync/database/backup-settings',
    method: 'put',
    data: data
  })
} 